<script setup lang="ts">
import { watch, ref, markRaw, onMounted, onUnmounted, inject } from "vue";
import leftCompWrapper from "../common/leftCompWrapper.vue";
import * as echarts from "echarts";
import { eqpTagBarChart } from "@/api/visual/visualConfig";
import dayjs from "dayjs";
defineOptions({
  name: "VChartBar"
});
const echartRef = ref();
let echartInstance: echarts.ECharts;
const isCollapsed = ref(false);
const props = withDefaults(
  defineProps<{
    propValue?: {
      contentList: Array<any>;
      title?: string;
      collapsed?: boolean;
      iconName?: string;
    };
    element?: {
      style: {
        width?: number;
        height?: number;
        display?: string;
      };
    };
  }>(),
  {
    propValue: () => ({
      contentList: [],
      title: "",
      collapsed: false,
      iconName: "alert"
    }),
    element: () => ({ style: {} })
  }
);

//const positionCode = inject("positionCode", "ROOM_22fc80");
const positionCode = inject("positionCode", ref(""));
watch(
  () => props.propValue.contentList,
  newVal => {
    renderChart(newVal as any);
  },
  { immediate: true }
);
onMounted(() => {
  echartInstance = markRaw(
    echarts.init(echartRef.value, undefined, {
      width: props.element!.style!.width! - 47,
      height: props.element.style.height! - 63
    })
  );
});
//数据初始化加接口请求
async function renderChart(newVal = []) {
  if (!newVal || newVal.length === 0) return;

  let data = deepCopy(newVal);
  // let data = [
  //   {
  //     tagNum: "TAG_aGK_p3bR"
  //   }
  // ];
  let tagNum = [data[0].tagNum];
  let rawData = { xaxis: [], yaxis: [] };
  let startTime = dayjs().startOf("day").format("YYYY-MM-DD HH:mm:ss");
  let endTime = dayjs().endOf("day").format("YYYY-MM-DD HH:mm:ss");
  const params = {
    tagNums: tagNum,
    positionCode: positionCode.value,
    startTime,
    endTime
  };
  if (tagNum) {
    rawData = await eqpTagBarChart(params);
  } else {
    echartInstance?.clear();
    return;
  }
  let { xaxis, yaxis } = rawData;

  try {
    let option = {
      tooltip: {
        trigger: "item"
      },
      grid: {
        top: "10%",
        bottom: "2%",
        left: "2%",
        right: "2%",
        containLabel: true
      },
      legend: {
        show: false
      },
      xAxis: {
        type: "category",
        data: deepCopy(xaxis),
        axisTick: {
          alignWithLabel: true
        },
        axisLabel: {
          color: "rgba(0,0,0,0.6)",
          rotate: -45,
          formatter: value => {
            return value.substring(11, value.length - 3);
          }
        }
      },
      yAxis: {
        type: "value",
        name: `电量（${yaxis[0] ? yaxis[0]["unit"] : "KVAh"}）`,
        nameTextStyle: {
          color: "rgba(0,0,0,0.4)"
        },
        axisLabel: {
          interval: 2,
          color: "rgba(0,0,0,0.4)"
        }
      },
      series: deepCopy(yaxis).map(item => {
        return {
          ...item,
          type: "bar",
          itemStyle: {
            color: "#4786FF"
          }
        };
      })
    };

    rednerRealChart(option as any);
    // 更新大小
  } catch (e) {
    console.error(e);
  }
}
//真实渲染数据处理数据
function rednerRealChart(option) {
  if (echartInstance && echartInstance.resize) {
    echartInstance.resize({
      width: props.element!.style!.width! - 47,
      height: props.element.style.height! - 63
    });

    let emptyOption = {
      title: {
        text: ""
      },
      series: []
    };

    // 配置参数
    echartInstance.clear();
    if (option.series.length > 0) echartInstance.setOption(option, true);
    else echartInstance.setOption(emptyOption, true);
  }
}
function deepCopy(data) {
  try {
    return JSON.parse(JSON.stringify(data));
  } catch (error) {
    console.error(error);
    return {};
  }
}
</script>

<template>
  <leftCompWrapper v-model="isCollapsed" :title="propValue.title" :icon-name="propValue.iconName" :has-collapsed="propValue.collapsed">
    <div class="w-[100%] h-[100%] pt-[5px]">
      <div ref="echartRef" />
    </div>
  </leftCompWrapper>
</template>

<style lang="scss" scoped>
.actions {
  display: flex;
  gap: 10px;
}
</style>
